# -*- coding: utf-8 -*-
'''
@author: Hugo
@file: css_teacher.py
@time: 2021/9/1 21:06
'''
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class CssOffset:
    def __init__(self):
       """初始化驱动"""
       option = webdriver.ChromeOptions()
       option.add_experimental_option('excludeSwitches', ['enable-automation'])
       option.add_argument('--disable-blink-features=AutomationControlled')
       self.driver = webdriver.Chrome(options=option)
       self.url = '''https://flight.qunar.com/site/oneway_list.htm?searchDepartureAirport=%E4%B8%8A%E6%B5%B7&searchArrivalAirport=%E5%8C%97%E4%BA%AC&searchDepartureTime=2021-09-03&searchArrivalTime=2021-09-06&nextNDays=0&startSearch=true&fromCode=SHA&toCode=BJS&from=flight_dom_search&lowestPrice=null'''
       self.wait = WebDriverWait(self.driver, 10)

    def get_flight_data(self):
          """获取机票数据"""
          script = "Object.defineProperty(navigator, 'webdriver', {get: () =>false,});"
          self.driver.get(self.url)
          self.driver.execute_script(script)
          divs = self.wait.until(EC.presence_of_all_elements_located((By.XPATH,
    '//div[@class="m-airfly-lst"]/div')))
          # divs = self.driver.find_elements_by_xpath('//div[@class="m-airfly-lst"]/div')
          return self.parse_line_data(divs)

    def parse_line_data(self, divs):
          """解析每条数据"""
          for div in divs:
                flight_name = div.find_element_by_xpath('.//div[@class="air"]').text
    # 机场
                begin_time = div.find_element_by_xpath('.//div[@class="sep-lf"]/h2').text   # 开始时间
                end_time = div.find_element_by_xpath('.//div[@class="sep-rt"]/h2').text    # 结束时间
                prices = div.find_elements_by_xpath('.//div[@class="col-price"]//em[@class="rel"]/b/i')   # 定位占位价格
                price = [price.text for price in prices]
                to_cover_prices = div.find_elements_by_xpath('.//div[@class="col-price"]//em[@class="rel"]/b')   # 定位补坑的
                to_cover_prices_and_styles = [
                     (to_cover_price.text, to_cover_price.get_attribute('style')) for
    to_cover_price in to_cover_prices[1:]
               ]
                true_price = self.replace_price(price, to_cover_prices_and_styles)
    # 休整价格
                # print([flight_name, f'{begin_time}-{end_time}', true_price])
                yield [flight_name, f'{begin_time}-{end_time}', true_price]

    @staticmethod
    def replace_price(price, to_cover_prices_and_styles):
         """将价格进行恢复"""
         for to_cover_price, to_cover_style in to_cover_prices_and_styles:
               left = re.search('width: 16px; left: -(\d+)px;',
    to_cover_style).group(1)   # 提取偏移距离
               price[-int(left) // 16] = to_cover_price
         return ''.join(price)


if __name__ == '__main__':
        css_offset = CssOffset()
        data = [line for line in css_offset.get_flight_data()]
        print(data)